package org.self.service.impl;

import io.jsonwebtoken.*;
import org.joda.time.DateTime;
import org.self.service.ITokenService;
import org.springframework.stereotype.Component;
import self.constance.Constance;

import java.util.Map;

/**
 * 作者: liYU
 * 项目名称: WX_Self_Iot_parent
 * 标题: TokenService
 * 该类描述: TODO
 * 创建日期: 2025/3/30
 */
@Component
public class TokenService implements ITokenService {

    @Override
    public String createToken(Map<String, Object> maps, String username, String id) {
        return Jwts.builder()
                //设置的是颁发者
                .setSubject(username)
                //设置用户id
                .setId(id)
                //设置token的过期时间
                .setExpiration(DateTime.now().plusSeconds(Constance.EXPIRE_TIME).toDate())
                .signWith(SignatureAlgorithm.HS512, Constance.JWT_SIGN)
                .compressWith(CompressionCodecs.GZIP)
                .compact();
    }

    @Override
    public Jws<Claims> parseToken(String token) {
        return Jwts.parser()
                   .setSigningKey(Constance.JWT_SIGN)
                   .parseClaimsJws(token);
    }

    @Override
    public boolean verifyToken(String token) {
        try {
            parseToken(token);
            return true;
        }catch (Exception err) {
            return false;
        }
    }

    @Override
    public String refreshToken(String token) {
        Jws<Claims> claimsJws = parseToken(token);
        Claims body = claimsJws.getBody();
        String username = body.getSubject();
        String id = body.getId();
        return createToken(null, username, id);
    }
}
